package com.raising.utils;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;

/**
 * 密码操作
 * @author gaoy
 */
@Service
public class PasswordUtils {

	private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

	private String algorithmName = "md5";
	/**Auto-Code*/
	public final static String PRE = "YD";
	private int hashIterations = 2;

	public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
		this.randomNumberGenerator = randomNumberGenerator;
	}

	public void setAlgorithmName(String algorithmName) {
		this.algorithmName = algorithmName;
	}

	public void setHashIterations(int hashIterations) {
		this.hashIterations = hashIterations;
	}

	/**
	 * 密码加密
	 * @author gaoyuan
	 * @param password 密码
	 */
	public PasswordEntity encryptPassword(String password) {
		String salt = randomNumberGenerator.nextBytes().toHex();
		String newPassword = new SimpleHash(algorithmName, password,
				ByteSource.Util.bytes(PRE + salt),
				hashIterations).toHex();
		return new PasswordEntity(newPassword,salt);
	}

	/**
	 * 获取加密后的密码
	 * @param password 加密前的密码
	 * @param salt 加密盐
	 * @return
	 */
	public String getPassword(String password,String salt) {
		return new SimpleHash(algorithmName, password, ByteSource.Util.bytes(PRE + salt), hashIterations).toHex();
	}

	/**
	 * 获取加密后的密码
	 * @param password 加密前的密码
	 * @param salt 加密盐
	 * @return
	 */
	public String getPassword(String password, ByteSource salt){
		return new SimpleHash(algorithmName, password, salt, hashIterations).toHex();
	}

	
	public static void main(String[] args) {
		PasswordUtils passwordUtils = new PasswordUtils();
		System.out.println(passwordUtils.getPassword("yd@123456","7425de50964f04bd815dd09aea806160"));
	}
}
